package com.fanrui.code.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

	private final AtomicInteger threadNumber;
	
	private final String threadNamePrefix;
	
	private ThreadGroup group;
	
	public NamedThreadFactory(String threadNamePrefix) {
		this.threadNamePrefix = threadNamePrefix;
		this.threadNumber = new AtomicInteger(1);
		SecurityManager s = System.getSecurityManager();
		this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
	}
	
	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(group, r, threadNamePrefix + threadNumber.getAndIncrement(), 0);
		if (t.isDaemon())
			t.setDaemon(false);
		if (t.getPriority() != Thread.NORM_PRIORITY)
			t.setPriority(Thread.NORM_PRIORITY);
		return t;
	}

}
